package com.powernode.service.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.powernode.constant.Constants;
import com.powernode.entity.Goods;
import com.powernode.entity.Orders;
import com.powernode.service.GoodsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;

/**
 * goods 业务实现类
 */
@Service
@Slf4j
public class GoodsServiceImpl implements GoodsService {

    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private ObjectMapper objectMapper;


    @Resource
    private RabbitTemplate rabbitTemplate;

    @Override
    public List<Goods> loadGoodsList() {
        log.info("从redis 中查询秒杀商品列表");
        // 定义一个返回列表
        ArrayList<Goods> goodsList = new ArrayList<>();
        // 从redis 中查询全部的key
        Set<String> keys = redisTemplate.keys(Constants.REDIS_GOODS + "*");
        // 遍历每一个key, 查询对应的商品信息
        keys.forEach(goodKey -> {
            // 查询该key对应的数据
            Goods goods = (Goods) redisTemplate.opsForValue().get(goodKey);
            // 不展示 随机码
            goods.setRandomName(null);
            // 将数据添加返回集合
            goodsList.add(goods);
        });
        return goodsList;
    }

    @Override
    public Goods loadGoodsById(Integer goodsid) {
        log.info("根据商品id从对应的redis缓存中查询对应的商品数据");
        return (Goods) redisTemplate.opsForValue().get(Constants.REDIS_GOODS + goodsid);
    }

    /**
     * 发送秒杀下单消息
     * @param goods
     * @param userId
     */
    @Override
    public void sendOrdersMessage(Goods goods, Integer userId) {
        Orders orders = new Orders();
        orders.setUid(userId);
        orders.setGoodsId(goods.getId());
        orders.setBuyNum(1);
        orders.setBuyPrice(goods.getPrice());
        orders.setCreateTime(new Date());
        orders.setStatus(0);
        // 将对象数据 转成json消息 作为生产者发送给 rabbitmq
        try {
            String message = objectMapper.writeValueAsString(orders);
            // 发送消息
            rabbitTemplate.convertAndSend(Constants.EXCHANGE_NAME_ORDER, Constants.ROUTING_KEY_ORDER, message);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }
}
